package com.zhangkunhao.notes.service;

import com.zhangkunhao.notes.dao.TopicPursueListDao;
import com.zhangkunhao.notes.entity.Do.*;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.service.impl.TopicPursueListService;
import com.zhangkunhao.notes.utils.IfValidInputUtil;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 话题关注列表接口的实现类
 *
 * @author 20642
 */
public class TopicPursueListServiceImpl implements TopicPursueListService {
    private QuestionServiceImpl questionService = new QuestionServiceImpl();

    @Override
    public List<TopicPursueList> selectAll() {
        return TopicPursueListDao.getInstance().findAll();
    }

    @Override
    public void insert(TopicPursueList topicPursueList) throws Exception {
        TopicPursueListDao.getInstance().insert(topicPursueList);
    }

    @Override
    public int delete(int id) throws SQLException {
        return TopicPursueListDao.getInstance().delete(id);
    }

    @Override
    public int update(TopicPursueList topicPursueList, String... params) throws Exception {
        return TopicPursueListDao.getInstance().update(topicPursueList);
    }

    public Message<TopicPursueList> pursueTopic(int userId, Topic topic) throws Exception {
        //初始化
        Message<TopicPursueList> pursueListMessage = new Message<>(null, "关注该话题失败", 0);
        //判断
        if (topic == null) {
            pursueListMessage.setResult("该话题为空，关注失败");
            return pursueListMessage;
        } else if (!IfValidInputUtil.ifValidValue(topic.getTopicName())) {
            pursueListMessage.setResult("该话题名称为空，关注失败");
            return pursueListMessage;
        }

        //调用dao
        this.insert(new TopicPursueList(null, topic.getId(), userId, topic.getTopicName()));

        //提供成功与否的判断
        boolean anyMatch = this.selectAll()
                .stream()
                .anyMatch(topicPursueList -> topicPursueList.getFollowerId().equals(userId) && topicPursueList.getTopicId().equals(topic.getId()));

        //成功
        if (anyMatch) {
            pursueListMessage.setResult("关注该话题成功");
            pursueListMessage.setStatus(1);
        }
        //返回数据
        return pursueListMessage;
    }

    public Message<TopicPursueList> cancelPursueTopic(int userId, Topic cancelTopic) throws Exception {
        //初始化
        Message<TopicPursueList> message = new Message<>(null, "取消关注话题失败", 0);
        //判断
        if (cancelTopic == null) {
            message.setResult("该话题为空，取消关注话题失败");
            return message;
        }

        //调用dao
        TopicPursueList topicPursueList = this.selectAll()
                .stream()
                .filter(topicPursueList1 -> topicPursueList1.getFollowerId().equals(userId) && topicPursueList1.getTopicId().equals(cancelTopic.getId()))
                .collect(Collectors.toList()).get(0);
        //调用dao
        int delete = this.delete(topicPursueList.getId());

        //成功
        if (delete > 0) {
            message.setResult("取消关注话题成功");
            message.setStatus(1);
        }
        return message;
    }

    public PageBean<Question> showMyPursueTopicQuestions(int userId) {
        //查询我已经关注的话题的名称
        List<String> topicNames = this.selectAll()
                .stream()
                .filter(topicPursueList -> topicPursueList.getFollowerId().equals(userId))
                .map(TopicPursueList::getTopicName)
                .collect(Collectors.toList());

        //没有关注过用户
        if (topicNames.isEmpty()) {
            return new PageBean<>(-1, null);
        }

        //查询所有合格的问题
        List<Question> questions = questionService.selectAll()
                .stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());
        Iterator<Question> it = questions.iterator();

        //是否问题是我关注的话题类型的问题
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (String topicName : topicNames) {
                if (question.getClassification().equals(topicName)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                //不能是userList.remove(user),会并发修改异常
                it.remove();
            }
        }

        if (!questions.isEmpty()) {
            return new PageBean<>(questions.size(), questions);
        } else {
            return new PageBean<>(0, null);
        }
    }

    public PageBean<Question> rankInterestedQuestionByLikes(int userId) {
        //查询我已经关注的话题的名称
        List<String> topicNames = this.selectAll().stream()
                .filter(topicPursueList -> topicPursueList.getFollowerId().equals(userId))
                .map(TopicPursueList::getTopicName)
                .collect(Collectors.toList());

        //没有关注过用户
        if (topicNames.isEmpty()) {
            return new PageBean<>(-1, null);
        }

        //查询所有合格的问题
        List<Question> questions = questionService.selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());
        Iterator<Question> it = questions.iterator();

        //是否问题是我关注的话题类型的问题
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (String topicName : topicNames) {
                if (question.getClassification().equals(topicName)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                //不能是userList.remove(user)
                it.remove();
            }
        }

        if (!questions.isEmpty()) {
            //排序
            List<Question> sortedQuestion = questions.stream().sorted((o1, o2) -> o2.getLikeCount() - o1.getLikeCount()).collect(Collectors.toList());
            return new PageBean<>(sortedQuestion.size(), sortedQuestion);
        } else {
            return new PageBean<>(0, null);
        }

    }

    public PageBean<Question> rankInterestedQuestionByLaunchTime(int userId) {
        //查询我已经关注的话题的名称
        List<String> topicNames = this.selectAll()
                .stream()
                .filter(topicPursueList -> topicPursueList.getFollowerId().equals(userId))
                .map(TopicPursueList::getTopicName)
                .collect(Collectors.toList());

        //没有关注过话题
        if (topicNames.isEmpty()) {
            return new PageBean<>(-1, null);
        }

        //查询所有合格的问题
        List<Question> questions = questionService.selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .collect(Collectors.toList());
        Iterator<Question> it = questions.iterator();

        //是否问题是我关注的话题类型的问题
        boolean isPursueList;

        while (it.hasNext()) {
            isPursueList = false;
            Question question = it.next();
            for (String topicName : topicNames) {
                if (question.getClassification().equals(topicName)) {
                    isPursueList = true;
                    break;
                }
            }
            if (!isPursueList) {
                //不能是userList.remove(user)
                it.remove();
            }
        }

        if (!questions.isEmpty()) {
            //排序
            List<Question> sortedQuestion = questions.stream().sorted((o1, o2) -> o2.getLaunchTime().compareTo(o1.getLaunchTime())).collect(Collectors.toList());
            return new PageBean<>(sortedQuestion.size(), sortedQuestion);
        } else {
            return new PageBean<>(0, null);
        }
    }
}
